package com.zhan.easyexcelorder.service.impl;

import com.zhan.easyexcelorder.listener.ExcelException;
import com.zhan.easyexcelorder.listener.ExcelListener;
import com.zhan.easyexcelorder.listener.ExcelUtils;
import com.zhan.easyexcelorder.model.SysDepartment;
import com.zhan.easyexcelorder.model.SysRole;
import com.zhan.easyexcelorder.model.SysUser;
import com.zhan.easyexcelorder.model.SysUserExcelEntity;
import com.zhan.easyexcelorder.repository.SysDepartmentRepository;
import com.zhan.easyexcelorder.repository.SysRoleRepository;
import com.zhan.easyexcelorder.repository.SysUserRepository;
import com.zhan.easyexcelorder.service.ExcelUser;
import com.zhan.utils.MyExceptionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.util.*;

/**
 * @author zhan
 * @since 2019-12-09 12:58
 */
@Service
public class ExcelUserImpl implements ExcelUser {
    /**
     * 导入用户时的默认密码
     */
    private final static String DEFAULT_PASSWORD = "123456";

    @Autowired
    private ExcelUser excelUser;

    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysRoleRepository sysRoleRepository;

    @Autowired
    private SysDepartmentRepository sysDepartmentRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * sheetNo 指定excel从具体的哪一个开始读取,本系统导入指定从第2 sheet导入
     *
     * @param excel
     * @throws ExcelException
     */
    @Transactional(rollbackOn = Exception.class)
    @Override
    public void importData(MultipartFile excel) throws ExcelException {
        List<SysUserExcelEntity> dataList = ExcelUtils.readExcel(excel, SysUserExcelEntity.class, 2, new ExcelListener(excelUser));
    }

    @Override
    public void saveData(List<SysUserExcelEntity> dataList) {
        if (!dataList.isEmpty()) {
            for (SysUserExcelEntity excelEntity : dataList) {
                checkRequiredFieldsCanBeNull(excelEntity);
                Map<String, Long> idMap = checkFieldsIsExist(excelEntity);

                SysUser sysUser = new SysUser();
                SysRole sysRole = new SysRole();
                SysDepartment department = new SysDepartment();

                sysUser.setUsername(excelEntity.getUsername());
                sysUser.setPassword(passwordEncoder.encode(DEFAULT_PASSWORD));
                sysUser.setPhone(excelEntity.getPhone());
                sysUser.setGeneralCode(excelEntity.getGeneralCode());
                sysUser.setSnatchCode(excelEntity.getSnatchCode());
                sysUser.setCreateTime(new Date());

                sysRole.setId(idMap.get("role_id"));
                department.setId(idMap.get("dept_id"));
                Set<SysRole> set = new HashSet<>();
                set.add(sysRole);
                sysUser.setRoles(set);

                sysUser.setDepartment(department);

                sysUserRepository.save(sysUser);
            }
        }
    }

    private void checkRequiredFieldsCanBeNull(SysUserExcelEntity excelUser) {
        if (StringUtils.isBlank(excelUser.getUsername())) {
            MyExceptionUtil.throwErrMessage("用户名不能为空");
        }
        if (StringUtils.isBlank(excelUser.getPhone())) {
            MyExceptionUtil.throwErrMessage("手机号不能为空");
        }
        if (StringUtils.isBlank(excelUser.getRoleName())) {
            MyExceptionUtil.throwErrMessage("角色类型不能为空");
        }
        if (StringUtils.isBlank(excelUser.getFullDepartmentName())) {
            MyExceptionUtil.throwErrMessage("部门不能为空");
        }
    }

    /**
     * 检测用户在库中是否存在
     *
     * @param excelUser
     */
    private Map<String, Long> checkFieldsIsExist(SysUserExcelEntity excelUser) {
        Map<String, Long> map = new HashMap<>(3);
        SysUser user = sysUserRepository.getUser(excelUser.getUsername(), excelUser.getPhone());
        if (user != null) {
            MyExceptionUtil.throwErrMessage("姓名或手机号有重复,无法导入");
        }
        if (StringUtils.isNotBlank(excelUser.getGeneralCode())) {
            String code = sysUserRepository.selectGeneralCode(excelUser.getGeneralCode());
            if (StringUtils.isNotBlank(code)) {
                MyExceptionUtil.throwErrMessage("上班普席工号有重复，无法导入");
            }
        } else if (StringUtils.isNotBlank(excelUser.getSnatchCode())) {
            String code = sysUserRepository.selectSnatchCode(excelUser.getSnatchCode());
            if (StringUtils.isNotBlank(code)) {
                MyExceptionUtil.throwErrMessage("抢班普席工号有重复，无法导入");
            }
        }
        SysRole sysRole = sysRoleRepository.getSysRolesByRoleName(excelUser.getRoleName());
        if (sysRole == null) {
            MyExceptionUtil.throwErrMessage("角色类型不存在，无法导入");
        }
        SysDepartment deptName = sysDepartmentRepository.getSysDepartmentByName(excelUser.getFullDepartmentName());
        if (deptName == null) {
            MyExceptionUtil.throwErrMessage("部门信息不粗真乃，无法导入");
        }
        map.put("role_id", sysRole.getId());
        map.put("dept_id", deptName.getId());
        return map;
    }
}
